package material

import (
	"context"
	"gitee.com/bobo-rs/idea-space-framework/framework/dao"
	"gitee.com/bobo-rs/idea-space-framework/framework/model"
	"gitee.com/bobo-rs/idea-space-framework/framework/model/entity"
	"gitee.com/bobo-rs/idea-space-framework/framework/service"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
)

// SaveMaterial 保存素材详情（添加|编辑）
func (m *sMaterial) SaveMaterial(ctx context.Context, in model.MaterialSaveInput) (out *model.MaterialSaveOutput, err error) {
	out = &model.MaterialSaveOutput{}
	// 获取附件详情
	attachDetail := model.MaterialAttachmentItem{}
	err = service.Attachment().ProcessAttachmentDetailByAttachId(
		ctx, in.AttachId, &attachDetail,
	)
	if err != nil {
		return nil, err
	}

	// 素材参数
	param := entity.Material{
		Id:           in.Id,
		MaterialType: uint(in.MaterialType),
		AttachId:     in.AttachId,
		Position:     string(in.Position),
		ChannelId:    in.ChannelId,
		MaterialName: attachDetail.RealName,
		Url:          attachDetail.AttUrl,
		Width:        attachDetail.Width,
		Height:       attachDetail.Height,
	}

	// 补充操作人信息
	adminUser := service.User().GetAdminUser(ctx)
	if param.Id == 0 && adminUser != nil {
		param.Creator = adminUser.ManageName
		param.CreatorId = adminUser.Id
	}
	if adminUser != nil {
		param.Modified = adminUser.ManageName
	}

	// 保存数据
	r, err := dao.Material.Ctx(ctx).OmitEmpty().Save(param)
	if err != nil {
		return nil, err
	}
	// 素材ID是否存在
	materialId, err := r.LastInsertId()
	if err != nil {
		return nil, gerror.Wrapf(err, `素材保存失败：%s`, err.Error())
	}
	out.Id = uint(materialId)
	return
}

// DeleteMaterial 删除素材
func (m *sMaterial) DeleteMaterial(ctx context.Context, materialId uint) (err error) {
	var (
		orm = dao.Material.Ctx(ctx).Where(dao.Material.Columns().Id, materialId)
	)
	// 是否存在
	if isMaterial, _ := m.CheckMaterialExistsById(ctx, materialId); !isMaterial {
		return gerror.New(`模板不存在`)
	}
	// 是否绑定模板false未绑定，true绑定模板
	switch m.CheckTemplateWordsExistsByMaterialId(ctx, materialId) {
	case false:
		_, err = orm.Delete()
	default:
		_, err = orm.Update(g.Map{dao.Material.Columns().Status: 1})
	}
	return err
}
